<template>
  <el-dialog :model-value="props.dialogvis" @update:dialogvis="(val) => emits('update:dialogvis', val)" title="定位设置"
    width="500" draggable :modal="false" overflow :close-on-click-modal="false" :append-to-body="true"
    :id="props.dioid">

    <el-form :model="form" label-width="auto" style="margin-top: 10px">
      <el-form-item label="单位">
        <el-radio-group @change="onChangedingwe" v-model="form.name">
          <el-radio value="经纬度">经纬度</el-radio>
          <el-radio value="度分秒">度分秒</el-radio>
          <el-radio value="像素">像素</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 经纬度/度分秒输入区域 -->
      <template v-if="form.name === '经纬度' || form.name === '度分秒'">
        <el-form-item label="经度">
          <el-input v-model="form.jing" />
        </el-form-item>
        <el-form-item label="纬度">
          <el-input v-model="form.wei" />
        </el-form-item>
      </template>

      <!-- 像素坐标输入区域 -->
      <template v-if="form.name === '像素'">
        <el-form-item label="像素X">
          <el-input v-model="form.pixelX" type="number" placeholder="请输入像素X坐标" />
        </el-form-item>
        <el-form-item label="像素Y">
          <el-input v-model="form.pixelY" type="number" placeholder="请输入像素Y坐标" />
        </el-form-item>
      </template>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="emits('update:dialogvis', false)">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, defineEmits, onMounted, onBeforeUnmount, getCurrentInstance,  nextTick } from "vue";
const { proxy } = getCurrentInstance();
const props = defineProps({
  dialogvis: Boolean,
  showDrawDialog: {
    type: Boolean,
    default: false,
  },
  dioid: {
    type: String,
    default: "",
  },
});
const emits = defineEmits(["update:dialogvis"]);
const dialogVisible = ref(false);
const form = ref({
  name: '经纬度',
  jing: '116.397222',
  wei: '39.908722',
  pixelX: 0,
  pixelY: 0
});

// 存储红点实体
let redPointEntity = null;

// 移除红点的函数
const removeRedPoint = () => {
  if (redPointEntity && window.viewer) {
    window.viewer.entities.remove(redPointEntity);
    redPointEntity = null;
  }
};

// 添加红点的函数
const addRedPoint = (longitude, latitude) => {
  // 如果已有红点，先移除
  removeRedPoint();

  // 添加新的红点
  if (window.viewer) {
    redPointEntity = window.viewer.entities.add({
      position: window.Cesium.Cartesian3.fromDegrees(longitude, latitude),
      point: {
        pixelSize: 10,
        color: window.Cesium.Color.RED,
        outlineColor: window.Cesium.Color.WHITE,
        outlineWidth: 2
      }
    });
  }
};

const submitForm = () => {
  let longitude, latitude;

  if (form.value.name === '像素') {
    // 像素坐标转经纬度
    const result = pixelToLonLat(form.value.pixelX, form.value.pixelY);
    longitude = result.longitude;
    latitude = result.latitude;

    if (longitude !== null && latitude !== null) {
      window.viewer.camera.flyTo({
        destination: window.Cesium.Cartesian3.fromDegrees(longitude, latitude, 1000000),
      });

      // 添加红点
      addRedPoint(longitude, latitude);
    } else {
      console.warn("像素坐标转换失败");
    }
  } else {
    // 处理经度
    const jing = parseCoordinate(form.value.jing);
    // 处理纬度
    const wei = parseCoordinate(form.value.wei);

    if (jing !== null && wei !== null) {
      longitude = jing;
      latitude = wei;

      window.viewer.camera.flyTo({
        destination: window.Cesium.Cartesian3.fromDegrees(jing, wei, 1000000),
      });

      // 添加红点
      addRedPoint(longitude, latitude);
    } else {
      console.warn("坐标格式错误");
    }
  }
  emits('update:dialogvis', false)
};

// 像素坐标转经纬度
const pixelToLonLat = (pixelX, pixelY) => {
  try {
    if (!window.viewer || !pixelX || !pixelY) return { longitude: null, latitude: null };

    // 获取画布尺寸
    const canvas = window.viewer.canvas;
    const width = canvas.clientWidth;
    const height = canvas.clientHeight;

    // 归一化坐标
    const x = pixelX / width;
    const y = pixelY / height;

    // 使用Cesium的坐标转换
    const pickRay = window.viewer.camera.getPickRay(new window.Cesium.Cartesian2(pixelX, pixelY));
    const cartesian = window.viewer.scene.globe.pick(pickRay, window.viewer.scene);
    const cartographic = window.Cesium.Cartographic.fromCartesian(cartesian);

    // 转换为经纬度
    const longitude = window.Cesium.Math.toDegrees(cartographic.longitude);
    const latitude = window.Cesium.Math.toDegrees(cartographic.latitude);

    return { longitude, latitude };
  } catch (e) {
    console.error('像素坐标转换错误:', e);
    return { longitude: null, latitude: null };
  }
};

// 监听像素坐标变化
watch(() => form.value.pixelX, (newVal) => {
  if (newVal < 0 || newVal > window.viewer?.canvas?.clientWidth) {
    console.warn('像素X坐标超出画布范围');
  }
});

watch(() => form.value.pixelY, (newVal) => {
  if (newVal < 0 || newVal > window.viewer?.canvas?.clientHeight) {
    console.warn('像素Y坐标超出画布范围');
  }
});



const onChangedingwe = (data) => {
  if (data === '经纬度') {
    // 转换为十进制
    form.value.jing = isDMS(form.value.jing) ? dmsToDD(form.value.jing) : form.value.jing;
    form.value.wei = isDMS(form.value.wei) ? dmsToDD(form.value.wei) : form.value.wei;
  } else if (data === '度分秒') {
    // 转换为度分秒
    form.value.jing = isDD(form.value.jing) ? decimalToDMS(form.value.jing) : form.value.jing;
    form.value.wei = isDD(form.value.wei) ? decimalToDMS(form.value.wei) : form.value.wei;
  }
  // 像素坐标不需要转换
};
//经纬度转度分秒
const decimalToDMS = (decimal) => {
  const deg = Math.floor(decimal);
  const minFloat = (decimal - deg) * 60;
  const min = Math.floor(minFloat);
  const sec = ((minFloat - min) * 60).toFixed(2);
  return `${deg}°${min}'${sec}"`;
}
//度分秒 转经纬度
const dmsToDD = (dmsString) => {
  // 正则匹配：度数、分数、秒数（支持负号）
  const match = dmsString.match(/^(-?\d+)°(\d+)'([\d.]+)"$/);
  if (!match) {
    throw new Error("Invalid DMS format");
  }

  const degrees = parseFloat(match[1]);
  const minutes = parseFloat(match[2]);
  const seconds = parseFloat(match[3]);

  // 计算十进制度
  const dd = Math.abs(degrees) + minutes / 60 + seconds / 3600;
  return degrees < 0 ? -dd : dd;
}
//
const isDMS = (coord) => {
  // 检查是否是字符串且符合度分秒格式
  return typeof coord === 'string' && /^-?\d+°\d+'[\d.]+"$/.test(coord);
};
//
const isDD = (coord) => {
  // 检查是否是数字或在合理范围内的数字字符串
  const num = typeof coord === 'string' ? parseFloat(coord) : coord;
  return !isNaN(num) && num >= -180 && num <= 180;
};

//
const parseCoordinate = (coord) => {
  try {
    if (isDMS(coord)) {
      // 度分秒转十进制
      return dmsToDD(coord);
    } else if (isDD(coord)) {
      // 已经是十进制，直接返回
      return typeof coord === 'string' ? parseFloat(coord) : coord;
    }
    throw new Error('无法识别的坐标格式');
  } catch (e) {
    console.error('坐标解析错误:', e);
    return null;
  }
};

// 添加鼠标右键监听器
let rightClickHandler = null;

// 添加一个函数来初始化右键事件监听器
const initRightClickHandler = () => {
  // 清理已存在的事件监听器
  if (rightClickHandler) {
    rightClickHandler.destroy();
    rightClickHandler = null;
  }

  // 初始化鼠标右键监听器
  if (window.viewer) {
    rightClickHandler = new window.Cesium.ScreenSpaceEventHandler(window.viewer.canvas);

    rightClickHandler.setInputAction(() => {
      removeRedPoint();
    }, window.Cesium.ScreenSpaceEventType.RIGHT_CLICK);
  }
};

onMounted(() => {
  // 检查 window.viewer 是否已经存在
  if (window.viewer) {
    initRightClickHandler();
  } else {
    // 如果 window.viewer 不存在，监听 cesiumInitialized 事件
    proxy.$mitt.on("cesiumInitialized", () => {
      // 使用 nextTick 确保在 DOM 更新后执行
      nextTick(() => {
        initRightClickHandler();
      });
    });
  }
});

onBeforeUnmount(() => {
  // 清理事件监听器
  if (rightClickHandler) {
    rightClickHandler.destroy();
    rightClickHandler = null;
  }

  // 组件销毁时移除红点
  removeRedPoint();

  // 移除事件监听器
  proxy.$mitt.off("cesiumInitialized", initRightClickHandler);
});
</script>